package com.monitor.filter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 进程过滤器，用于禁止运行指定程序
 */
public class ProcessFilter implements ContentFilter {
    private FilterSensitivity sensitivity = FilterSensitivity.MEDIUM;
    private List<String> blockedProcesses = new ArrayList<>();
    
    public ProcessFilter() {
        // 初始化默认禁止进程列表
        initDefaultBlockedProcesses();
    }
    
    private void initDefaultBlockedProcesses() {
        // 添加一些默认的禁止进程
        blockedProcesses.add("game.exe");
        blockedProcesses.add("chat.exe");
        blockedProcesses.add("gambling.exe");
    }
    
    @Override
    public boolean containsInappropriateContent(String processName) {
        if (processName == null || processName.isEmpty()) {
            return false;
        }
        
        // 根据灵敏度级别调整匹配策略
        switch (sensitivity) {
            case HIGH:
                return highSensitivityCheck(processName);
            case MEDIUM:
                return mediumSensitivityCheck(processName);
            case LOW:
                return lowSensitivityCheck(processName);
            default:
                return mediumSensitivityCheck(processName);
        }
    }
    
    private boolean highSensitivityCheck(String processName) {
        // 高灵敏度：部分匹配即可
        for (String blockedProcess : blockedProcesses) {
            if (processName.toLowerCase().contains(blockedProcess.toLowerCase())) {
                return true;
            }
        }
        return false;
    }
    
    private boolean mediumSensitivityCheck(String processName) {
        // 中灵敏度：文件名匹配
        String fileName = extractFileName(processName);
        for (String blockedProcess : blockedProcesses) {
            if (fileName.equalsIgnoreCase(blockedProcess) || 
                fileName.equalsIgnoreCase(extractFileName(blockedProcess))) {
                return true;
            }
        }
        return false;
    }
    
    private boolean lowSensitivityCheck(String processName) {
        // 低灵敏度：完全匹配
        for (String blockedProcess : blockedProcesses) {
            if (processName.equalsIgnoreCase(blockedProcess)) {
                return true;
            }
        }
        return false;
    }
    
    private String extractFileName(String path) {
        // 提取文件名
        int lastSeparatorIndex = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
        if (lastSeparatorIndex != -1) {
            return path.substring(lastSeparatorIndex + 1);
        }
        return path;
    }
    
    /**
     * 获取当前运行的进程列表
     * @return 进程名称列表
     */
    public List<String> getRunningProcesses() {
        List<String> processes = new ArrayList<>();
        try {
            Process process;
            if (System.getProperty("os.name").toLowerCase().contains("windows")) {
                // 使用ProcessBuilder代替Runtime.exec，避免命令参数解析问题
                ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "tasklist", "/fo", "csv", "/nh");
                processBuilder.redirectErrorStream(true);
                process = processBuilder.start();
                
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    // CSV格式解析，第一列是进程名称
                    if (line.contains(",")) {
                        String[] parts = line.split(",");
                        if (parts.length > 0) {
                            // 去除引号
                            String procName = parts[0].replace("\"", "");
                            processes.add(procName);
                        }
                    } else {
                        processes.add(line);
                    }
                }
                reader.close();
            } else {
                // 对于非Windows系统，使用ProcessBuilder执行ps命令
                ProcessBuilder processBuilder = new ProcessBuilder("ps", "-e");
                processBuilder.redirectErrorStream(true);
                process = processBuilder.start();
                
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    // 对于非Windows系统，提取最后一列作为进程名
                    String[] parts = line.trim().split("\\s+");
                    if (parts.length > 0) {
                        String procName = parts[parts.length - 1];
                        processes.add(procName);
                    } else {
                        processes.add(line);
                    }
                }
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return processes;
    }
    
    /**
     * 终止指定进程
     * @param processName 进程名称
     * @return 是否成功终止
     */
    public boolean killProcess(String processName) {
        try {
            if (System.getProperty("os.name").toLowerCase().contains("windows")) {
                Runtime.getRuntime().exec("taskkill /F /IM " + processName);
            } else {
                Runtime.getRuntime().exec("pkill -f " + processName);
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public String getFilterName() {
        return "进程过滤器";
    }
    
    @Override
    public String getFilterDescription() {
        return "禁止运行指定程序（如网络游戏、聊天软件）";
    }
    
    @Override
    public void setSensitivity(FilterSensitivity sensitivity) {
        this.sensitivity = sensitivity;
    }
    
    @Override
    public FilterSensitivity getSensitivity() {
        return sensitivity;
    }
    
    /**
     * 添加禁止进程
     * @param processName 进程名称
     */
    public void addBlockedProcess(String processName) {
        if (processName != null && !processName.isEmpty() && !blockedProcesses.contains(processName)) {
            blockedProcesses.add(processName);
        }
    }
    
    /**
     * 移除禁止进程
     * @param processName 进程名称
     */
    public void removeBlockedProcess(String processName) {
        blockedProcesses.remove(processName);
    }
    
    /**
     * 获取所有禁止进程
     * @return 禁止进程列表
     */
    public List<String> getBlockedProcesses() {
        return new ArrayList<>(blockedProcesses);
    }
}